/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.web.controller;

import com.bifrost.annotation.Authorization;
import com.bifrost.annotation.CurrentUser;
import com.bifrost.authorization.manager.impl.RedisTokenManager;
import com.bifrost.entity.BonusPointsHistory;
import com.bifrost.entity.Customer;
import com.bifrost.common.model.ResultModel;
import com.bifrost.entity.MerchantStore;
import com.bifrost.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Date: 2017/9/28
 * Time: 22:39
 *
 * @author joewee
 * @version 1.0.0
 */
@RestController
@RequestMapping(value = "/api/customer")
@Api("会员相关接口")
public class CustomerController {

    @Autowired
    CustomerService customerService;
    @Autowired
    RegAndLogService regAndLogService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SmsService smsService;
    @Autowired
    RedisTokenManager redisTokenManager;
    @Autowired
    MediaService mediaService;
    @Autowired
    BonusPointsService bonusPointsService;

    @ApiOperation(value = "发送手机验证码")
    @ApiImplicitParam(paramType = "query", name = "customerPhone", value = "用户手机号码", required = true, dataType = "String")
    @PostMapping("/sendMessage")
    public ResultModel sendMessage(@RequestParam String customerPhone) {
        return smsService.sendMessage(customerPhone);
    }

    @ApiOperation(value = "校验手机验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customerPhone", value = "手机号码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "message", value = "验证码", required = true, dataType = "String")
    })
    @PostMapping("/validateMessage")
    public ResultModel validateMessage(@RequestParam String customerPhone, @RequestParam String message) {
        Boolean flag = smsService.checkMessage(customerPhone, message);
        if (Boolean.FALSE.equals(flag)) {
            return ResultModel.error("验证错误或已失效");
        }
        return ResultModel.ok();
    }

    @ApiOperation(value = "用户注册", notes = "通过验证码实现用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "message", value = "验证码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "customerPhone", value = "手机号码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "customerPassword", value = "密码（密文）", required = true, dataType = "String")
    })
    @PostMapping("/regist")
    public ResultModel userRegist(@RequestParam String customerPhone, @RequestParam String message,
                                  @RequestParam String customerPassword, HttpServletRequest request, HttpServletResponse response) {
        return regAndLogService.regist(customerPhone,message,customerPassword,request,response);
    }

    @ApiOperation(value = "用户登录：密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customerPhone", value = "用户名（手机号码）", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "customerPassword", value = "密码（密文）", required = true, dataType = "String")
    })
    @PostMapping("/login")
    public ResultModel userLoginWithPwd(@RequestParam String customerPhone, @RequestParam String customerPassword, HttpServletResponse response, HttpServletRequest request) {
        return regAndLogService.loginWithPwd(customerPhone, customerPassword, response, request);
    }

    @ApiOperation(value = "用户登录：验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customerPhone", value = "用户名（手机号码）", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "validateCode", value = "验证码", required = true, dataType = "String")
    })
    @PostMapping("/logWithCode")
    public ResultModel userLoginWithCode(@RequestParam String customerPhone, @RequestParam String validateCode, HttpServletResponse response, HttpServletRequest request) {
        return regAndLogService.loginWithCode(customerPhone, validateCode, response, request);
    }


    @Authorization
    @ApiOperation(value = "用户注销")
    @PostMapping("/logout")
    public ResultModel logOut(@CurrentUser Long userId, HttpServletResponse response) {
        Customer customer = customerService.findCustomer(userId);
        return regAndLogService.logout(customer, response);
    }

    @Authorization
    @ApiOperation(value = "用户积分历史记录")
    @GetMapping("/bonusPointsHistories")
    public ResultModel bonusPointsHistories(@CurrentUser Long userId,
                                            @RequestParam(value = "page", defaultValue = "1")Integer page,
                                            @RequestParam(value = "pageSize", defaultValue = "10")Integer pageSize) {
        Customer customer = customerService.findCustomer(userId);
        String loyaltyCard = customer.getLoyaltyCard();
        MerchantStore store = customer.getMerchantStore();
        Page<BonusPointsHistory> data = bonusPointsService.getBonusPointsHistories(loyaltyCard, store.getMerchantId(), page, pageSize);
        if(null != data && data.hasContent()){
            List<BonusPointsHistory> bonusPointsHistoryList = data.getContent();
            if (CollectionUtils.isNotEmpty(bonusPointsHistoryList)) {
                List<Map<String, Object>> histories = new ArrayList<>(10);
                for (BonusPointsHistory h : bonusPointsHistoryList) {
                    Map<String, Object> map = new HashMap<String, Object>(8);
                    map.put("cardNumber", loyaltyCard);
                    map.put("updatedTimestamp", h.getUpdatedTimestamp());
                    map.put("source", h.getSource().name());
                    map.put("type", h.getUpdatedType().name());
                    map.put("afterValue", h.getAfterValue());
                    map.put("updatedValue", h.getUpdatedValue());
                    map.put("remark", h.getRemark());
                    histories.add(map);
                }
                return ResultModel.ok()
                        .put("total", data.getTotalElements())
                        .put("page", data.getNumber())
                        .put("pageSize", data.getSize())
                        .put("totalPages", data.getTotalPages())
                        .put("histories", histories);
            }
        }
        return ResultModel.error("暂无积分记录");
    }
}
